<template>
  <ElementDialog
    title="选择用户"
    width="80%"
    height="500px"
    :body-padding="false"
    show-full-screen
    :visible.sync="visible">
    <ElRow :span="24" class="select-user">
      <ElCol :xs="24" :sm="24" :md="5" class="user__tree">
        <FyTree :option="treeOption" :data="treeData" @node-click="nodeClick">
          <template #default="{ node, data }">
            <span class="el-tree-node__label">
              <ElTooltip v-if="data.isLock" class="item" effect="dark" content="无数据权限" placement="right-start">
                <span>{{ node.label }} <i class="el-icon-lock"></i></span>
              </ElTooltip>
              <span v-if="!data.isLock">{{ node.label }}</span>
            </span>
          </template>
        </FyTree>
      </ElCol>
      <ElCol :xs="24" :sm="24" :md="19" class="user__main">
        <FyCurd
          ref="crud"
          v-model="form"
          :option="option"
          :page.sync="page"
          :table-loading="listLoading"
          :data="list"
          right-search
          @selection-change="selectionChange"
          @on-load="getList"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @size-change="sizeChange"
          @current-change="currentChange">
          <template #username="scope">
            <span>{{ scope.row.username }}</span>
          </template>
          <template #role="scope">
            <span v-for="(item, index) in scope.row.roleList" :key="index">
              <ElTag>{{ item.roleName }} </ElTag>&nbsp;&nbsp;
            </span>
          </template>
          <template #deptId="scope">
            {{ scope.row.deptName }}
          </template>
          <template #lockFlag="scope">
            <ElTag>{{ scope.label }}</ElTag>
          </template>
        </FyCurd>
      </ElCol>
    </ElRow>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" @click="checkRowData">确定</ElButton>
      </span>
    </template>
  </ElementDialog>
</template>

<script>
  import { fetchList, selectUserList } from '@/api/admin/user'
  import { deptRoleList } from '@/api/admin/role'
  import { fetchTree } from '@/api/admin/dept'
  import { mapState } from 'vuex'

  export default {
    name: 'SelectUser',
    props: {
      selectType: {
        type: String,
        default: 'default'
      },
      // 允许选择的条数
      allowChooseNum: {
        type: Number,
        default: 1
      }
    },
    data() {
      return {
        searchForm: {},
        treeOption: {
          nodeKey: 'id',
          addBtn: false,
          menu: false,
          props: {
            label: 'name',
            value: 'id'
          }
        },
        treeData: [],
        option: tableOption,
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 15, // 每页显示多少条,
          isAsc: false // 是否倒序
        },
        list: [],
        listLoading: true,
        role: [],
        form: {},
        rolesOptions: [],
        resultData: [],
        visible: false
      }
    },
    computed: {
      ...mapState('user', ['permissions'])
    },
    watch: {
      role() {
        this.form.role = this.role
      }
    },
    // created() {
    //   this.init()
    // },
    methods: {
      init() {
        this.visible = true
        fetchTree().then(response => {
          this.treeData = response.data.data
        })
      },
      nodeClick(data) {
        this.page.page = 1
        this.searchForm.deptId = data.id
        this.getList(this.page, { deptId: data.id })
      },
      getList(page, params) {
        this.listLoading = true
        // 选择Userinfo表没有的 user信息
        if (this.selectType !== 'default') {
          selectUserList(
            Object.assign(
              {
                current: page.currentPage,
                size: page.pageSize
              },
              params,
              this.searchForm
            ),
            this.selectType
          ).then(response => {
            this.list = response.data.data.records
            this.page.total = response.data.data.total
            this.listLoading = false
          })
        } else {
          fetchList(
            Object.assign(
              {
                current: page.currentPage,
                size: page.pageSize
              },
              params,
              this.searchForm
            )
          ).then(response => {
            this.list = response.data.data.records
            this.page.total = response.data.data.total
            this.listLoading = false
          })
        }
      },
      getNodeData() {
        deptRoleList().then(response => {
          this.rolesOptions = response.data.data
        })
      },
      searchChange(param, done) {
        this.searchForm = param
        this.page.currentPage = 1
        this.getList(this.page, param)
        done()
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      currentChange(current) {
        this.page.currentPage = current
      },
      refreshChange() {
        this.getList(this.page)
      },
      selectionChange(list) {
        // this.$message.success('选中的数据 ' + JSON.stringify(list))
        if (this.allowChooseNum > 0) {
          if (list.length > this.allowChooseNum) {
            this.toggleSelection(list)
            this.$message.success(`只能选择${this.allowChooseNum}条`)
            return
          }
        }
        this.resultData = list
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.crud.toggleRowSelection(row)
          })
        } else {
          this.$refs.crud.clearSelection()
        }
      },
      // 选择行数据
      checkRowData() {
        if (this.allowChooseNum === 1) {
          this.$emit('getUserData', this.resultData[0])
        } else {
          this.$emit('getUserData', this.resultData)
        }
        this.visible = false
      }
    }
  }

  const tableOption = {
    border: true,
    index: true,
    indexLabel: '序号',
    stripe: true,
    menuAlign: 'center',
    searchMenuSpan: 6,
    editBtn: false,
    delBtn: false,
    align: 'center',
    addBtn: false,
    menu: false,
    selection: true,
    column: [
      {
        fixed: true,
        label: 'id',
        prop: 'userId',
        hide: true,
        editDisabled: true,
        addDisplay: false
      },
      {
        fixed: true,
        label: '登录名称',
        prop: 'username',
        editDisabled: true,
        slot: true,
        search: true
      },
      {
        label: '姓名',
        prop: 'realName',
        search: true
      },
      {
        label: '密码',
        prop: 'password',
        type: 'password',
        value: '',
        hide: true
      },
      {
        label: '所属部门',
        prop: 'deptId',
        formslot: true,
        slot: true,
        hide: true,
        dataType: 'number'
      },
      {
        label: '手机号',
        prop: 'phone',
        type: 'input',
        value: ''
      },
      {
        label: '角色',
        prop: 'role',
        formslot: true,
        slot: true,
        overHidden: true
      },
      {
        label: '状态',
        prop: 'lockFlag',
        type: 'radio',
        slot: true,
        border: true,
        rules: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'blur'
          }
        ],
        dicData: [
          {
            label: '有效',
            value: '0'
          },
          {
            label: '锁定',
            value: '9'
          }
        ]
      },
      {
        width: 180,
        label: '创建时间',
        prop: 'createTime',
        type: 'datetime',
        format: 'yyyy-MM-dd HH:mm',
        valueFormat: 'yyyy-MM-dd HH:mm:ss',
        editDisabled: true,
        addDisplay: false,
        span: 24
      }
    ]
  }
</script>

<style lang="scss">
  .select-user {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 20px;
    }

    &__main {
      .el-card__body {
        padding-top: 0;
      }
    }
  }
</style>
